package com.gaxy.wechat.controller;

import com.gaxy.wechat.handler.WeChatMsgFactory;
import com.gaxy.wechat.handler.WeChatMsgHandler;
import com.gaxy.wechat.utils.MessageUtil;
import com.gaxy.wechat.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 微信服务controller
 *
 * @author Gaxy
 * @create 2024/06/12/下午 08:34
 */
@RestController
@Slf4j
public class CallBackController {

    private static final String TOKEN = "geeklub_wechat_token";

    @Resource
    private WeChatMsgFactory weChatMsgFactory;

    /**
     * 回调消息校验
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */

    @GetMapping("/callBack")
    public String callBack(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("GET验签请求参数:signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String sha1 = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
        if (signature.equals(sha1)) {
            return echostr;
        }
        return "false";
    }

    @PostMapping(value = "/callBack", produces = "application/xml;charset=UTF-8")
    public String callBack(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信请求参数:requestBody:{},signature:{}，timestamp:{}，nonce:{}",
                requestBody, signature, timestamp, nonce);
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        String msgType = msgMap.get("MsgType");
        String event = msgMap.get("Event") == null ? "" : msgMap.get("Event");
        log.info("msgType:{}, event:{}", msgType, event);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(msgType);  //如果msgType是Text，则不做处理；如果msgType是Event，还需要拼接一个".subscribe"
        if (!StringUtils.isEmpty(event)) {  //拼接".subscribe"
            stringBuilder.append(".");
            stringBuilder.append(event);    //event.subscribe
        }
        String msgTypeKey = stringBuilder.toString();

        WeChatMsgHandler weChatMsgHandler = weChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(weChatMsgHandler)) {
            return "找不到对应的handler";
        }
        String replyContent = weChatMsgHandler.dealMsg(msgMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }

}
